﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Caching;
using System.Data;
using Telerik.Web.UI;
using System.Data.Common;
public partial class Admin_Components_Member_Function : System.Web.UI.UserControl
{
    DataTable dt = new DataTable();
    int ParentID = 20; //ID trong CSDL, bảng Function
    static int FormState = -1; //trạng thái form ban đầu
    string ID = "";
    string i_UserID;
    int idedit;
    protected void Page_Load(object sender, EventArgs e)
    {
        
        i_UserID = Session["UserName"].ToString();//huy add
        if (Session["FunctionID"] == null)
            FormState = 0;
        else
            FormState = 1;

        if (!IsPostBack)
        {
            txtOderal.Text = "1";
            SetupForm();
            switch (FormState)
            {
                case 0:
                    {
                        break;
                    }
                default:
                    {
                        ID = Session["FunctionID"].ToString();
                        LoadDatatoForm();
                        LoadListFunction_ParentID();
                        break;
                    }
            }
        }
    
        Session.Remove("FunctionID");

    }
    protected void SetupForm()
    {
        
        //Load dữ liệu cho các control khi vừa load form
        ControlUtil.ForComboHierarchy<Function>(cboFunctionParent, "Không có",false);
        ControlUtil.ForComboByCodeDetail(cboFunctionType, "FunctionType", "- Chọn -");
        ControlUtil.ForComboByCodeDetail(cboSystemFunction, "SystemFunction", "- Chọn -");

        cboFunctionParent.SelectedIndex = 0;
        cboFunctionType.SelectedIndex = 0;
        cboFunctionLevel.SelectedIndex = 0;
        txtOderal.Text = "1";
        SetEnable();
        LoadListFunction_ParentID();

        
    }

    protected void ClearForm()
    {
        cboFunctionLevel.SelectedIndex = 0;
        cboFunctionParent.SelectedIndex = 0;
        cboFunctionType.SelectedIndex = 0;
        txtFunctionName.Text = "";
        txtOderal.Text = "1";
        txtWebScreen.Text = "";
        txtFunctionCode.Text = "";
        radPublicFunction.Checked = true;
        FormState = 0;
    }

    protected void SetEnable()
    {
        switch (FormState)
        {
            case 0://Thêm mới
                {
                    btnGotoList.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;
                    break;
                }
            case 1://Sửa/Xóa
                {
                    btnGotoList.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;
                    break;
                }
            default://Chỉ xem
                {
                    btnGotoList.Visible = false;
                    btnNew.Visible = false;
                    btnSave.Visible = false;
                    break;
                }
        }
    }

    protected void LoadDatatoForm()
    {
        
        DBDataContext db = LINQUtil.GetDBReadOnly();
        var q = db.Function_Load(ID).ToList();

        if (q.Count == 1)
        {
            var t = q.FirstOrDefault();
            ControlUtil.ForComboHierarchySelectedValue(cboFunctionParent, Convert.ToString(t.ParentID));
            cboFunctionLevel.Text = t.FunctionLevel.ToString();
            cboFunctionLevel.SelectedValue = t.FunctionLevel.ToString();
            cboFunctionType.SelectedValue = t.FunctionType.ToString();
            txtFunctionCode.Text = t.ID.ToString();
            txtFunctionName.Text = t.FunctionName.ToString();
            txtOderal.Text = t.Ordinal.ToString();
            txtWebScreen.Text = t.WebScreen.ToString();
            txtMethodName.Text = t.MethodName.ToString();
            txtGroupID.Text = t.GroupID.ToString();
            cboMenuDisplay.SelectedValue = t.IsVisible.ToString();
            cboCheckRole.SelectedValue = t.IsCheck.ToString();
            string IsSysFunction = t.IsSysFunction.ToString();
            if (IsSysFunction == "True")
            {
                radSysFunction.Focus();
            }
            else
            {
                radPublicFunction.Focus();
            }
        }
    }

    protected void SaveData()
    {
        
       
        string funtion_id = txtFunctionCode.Text;
        if (txtFunctionCode.Text == null || txtFunctionCode.Text == "")
            FormState = 0;
        else
            FormState = 1;
        if (txtFunctionName.Text == "")
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Tên chức năng không được rỗng!");
            txtFunctionName.Focus();
                
            return;
        }
        if (txtWebScreen.Text == "")
        {
            txtWebScreen.Focus();
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Đường dẫn không được rỗng!");
                
            return;
        }
        if (txtGroupID.Text == "")
        {
            txtGroupID.Focus();
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Nhóm chức năng không được rỗng !");
            return;
        }

        //bỏ những ký tự đặc biệt, chống SQL Injection
        txtFunctionName.Text = Utils.KillChars(txtFunctionName.Text);
        txtOderal.Text = Utils.KillChars(txtOderal.Text);
        cboFunctionType.Text = Utils.KillChars(cboFunctionType.Text);
        cboFunctionParent.Text = Utils.KillChars(cboFunctionParent.Text);
        cboFunctionLevel.Text = Utils.KillChars(cboFunctionLevel.Text);
        txtWebScreen.Text = Utils.KillChars(txtWebScreen.Text);

        bool FunctionIsSysFun = false;
        if (radPublicFunction.Checked == true)
            FunctionIsSysFun = false;
        else
            FunctionIsSysFun = true;


        DBDataContext db = LINQUtil.GetDBWriteOnly();
        Function f = new Function();
        if (funtion_id.Length!=0)
        {
            //add thuộc tính ID để cập nhật
            ID = txtFunctionCode.Text;
            int id = int.Parse( Utils.KillChars(ID));

            f = db.Functions.FirstOrDefault(x => x.ID == id);

            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Cập nhật thành công");
        }
        f.CreatedBy = i_UserID;
        f.CreatedDateTime = DateTime.Now;
        f.FunctionLevel = int.Parse(cboFunctionLevel.SelectedValue);
        f.FunctionName = txtFunctionName.Text;
        f.FunctionType = cboFunctionType.SelectedValue;
        f.GroupID = int.Parse(txtGroupID.Text);
        f.GroupOrdinal = 0;
        f.IsSysFunction = FunctionIsSysFun;
        f.LastUpdatedBy = i_UserID;
        f.LastUpdatedDateTime = DateTime.Now;
        f.MethodName = txtMethodName.Text;
        f.Ordinal = int.Parse(txtOderal.Text);
        f.ParentID = int.Parse(ControlUtil.ForComboHierarchySelectedValue(cboFunctionParent) == "" ? "0" : ControlUtil.ForComboHierarchySelectedValue(cboFunctionParent));
        f.Status = 'A';
        f.SystemFunction = "INS";
        f.Type = char.Parse(cboFunctionType.SelectedValue);
        f.WebScreen = txtWebScreen.Text;
        f.IsCheck = bool.Parse(cboCheckRole.SelectedValue.ToString());
        f.IsVisible = bool.Parse(cboMenuDisplay.SelectedValue.ToString());

        if (funtion_id.Length == 0)
        {
            db.Functions.InsertOnSubmit(f);
            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thêm mới thành công !");
            FormState = 1;
        }
        else
        {
                
            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Cập nhật thành công");
        }
        db.SubmitChanges();
      

    }

  

    protected Boolean CheckAllBeforeSave()
    {
        Boolean flag = true;
        if (txtFunctionName.Text == "")
        {
            //lblResult.Text = "[Tên danh mục] không được rỗng";
            flag = false;
        }
        return flag;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        SaveData();
        LoadListFunction_ParentID();
        Response.Redirect(Request.RawUrl);
        
    }
    
    protected void btnNew_Click(object sender, EventArgs e)
    {
        
        ClearForm();
        SetEnable();
        btnSave.Enabled = true;
        btnGotoList.Focus();

    }
    protected void btnGotoList_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/FunctionList");
    }
    protected void cboFunctionType_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        cboFunctionParent.Focus();
    }


    private void LoadListFunction_ParentID()
    {
        DBDataContext db = LINQUtil.GetDBReadOnly();

        int ParentID = int.Parse(ControlUtil.ForComboHierarchySelectedValue(cboFunctionParent) == "" ? "0" : ControlUtil.ForComboHierarchySelectedValue(cboFunctionParent));
        string SystemFunction = cboSystemFunction.SelectedValue;
        var q = db.Function_Search_ParentID(ParentID, SystemFunction).ToList();

        this.gv.DataSource = q;
        this.gv.DataBind();
        this.gv.Visible = true;
        if (Session["UserName"].ToString() == "taipm")
        {
            lblQuery.Text = "Function_Search_ParentID " + ParentID + ",'" + SystemFunction + "'";
        }
        else
        {
            lblQuery.Text = "";
        }
    }


    protected void cboFunctionParentOnNodeClick(object sender, RadTreeNodeEventArgs e)
    {
        FormState = 0;

        int i_test = int.Parse(ControlUtil.ForComboHierarchySelectedValue(cboFunctionParent) == "" ? "0" : ControlUtil.ForComboHierarchySelectedValue(cboFunctionParent));
        LoadListFunction_ParentID();
        txtFunctionName.Focus();
    }

    protected void cboFunctionParent_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        
        FormState = 0;
        int i_test = int.Parse(ControlUtil.ForComboHierarchySelectedValue(cboFunctionParent) == "" ? "0" : ControlUtil.ForComboHierarchySelectedValue(cboFunctionParent));
        LoadListFunction_ParentID();
        ControlUtil.ForComboHierarchyByCode<Function>(cboFunctionParent, cboSystemFunction.SelectedValue.ToString(), "Không có",false);
        txtFunctionName.Focus();
    }

    protected void grvData_ItemCommand(object sender, GridCommandEventArgs e)
    {

        DBDataContext db = LINQUtil.GetDBWriteOnly();
        string commandName = e.CommandName;


        if (commandName == "EditDelItem")
        {
            try
            {
                int iRow = e.Item.ItemIndex;
                Session["FunctionID"] = gv.Items[iRow]["ID"].Text.Replace("&nbsp;", "");
                int functionID = int.Parse(Session["FunctionID"].ToString());
                Function f = db.Functions.FirstOrDefault(x => x.ID == functionID);
                f.Status = ObjectStatus.Invisible;
                db.SubmitChanges();
            
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa thành công");
            }
            catch (Exception ex)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thông báo lỗi: Xóa không thành công. Mã lỗi: CodeDetail - " + ex.Message);
            }
            LoadListFunction_ParentID();
            FormState = 1;
         
        }
        if (commandName == "EditItem")
        {
            FormState = 1;
            int iRow = e.Item.ItemIndex;
            Session["FunctionID"] = gv.Items[iRow]["ID"].Text.Replace("&nbsp;", "");
            idedit = int.Parse(gv.Items[iRow]["ID"].Text);
            txtFunctionName.Text = gv.Items[iRow]["FunctionName"].Text.Replace("nbsp;", "");
            cboFunctionLevel.SelectedValue = gv.Items[iRow]["FunctionLevel"].Text.Replace("nbsp;", "");
            txtGroupID.Text = gv.Items[iRow]["GroupID"].Text.Replace("nbsp;", "");
            txtWebScreen.Text = gv.Items[iRow]["WebScreen"].Text.Replace("nbsp;", "");
            txtOderal.Text = gv.Items[iRow]["Ordinal"].Text.Replace("nbsp;", "");
            txtFunctionCode.Text = gv.Items[iRow]["ID"].Text.Replace("nbsp;", "");
            cboFunctionType.SelectedValue = gv.Items[iRow]["FunctionType"].Text.Replace("nbsp;", "");
            cboFunctionParent.Text = gv.Items[iRow]["ParentID"].Text.Replace("nbsp;", "");
            cbType.Checked = gv.Items[iRow]["Type"].Text == FunctionType.Report ? true : false;

            GridEditableItem item = e.Item as GridEditableItem;
            CheckBox chkIsSysFunction = item.FindControl("chkIsSysFunction") as CheckBox;
            if (chkIsSysFunction.Checked == true)
            {

                radSysFunction.Checked = true;
                radPublicFunction.Checked = false;
            }
            else
            {

                radPublicFunction.Checked = true;
                radSysFunction.Checked = false;
            }
            // btnUpdate.Enabled = false;
            //btnUpdate.CssClass =  "Enable";
            btnSave.Enabled = true;
            btnSave.CssClass = "btn btn-sm btn-warning";


        }
       
    }
   
    protected void grvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
    }
    protected void txtFunctionName_TextChanged(object sender, EventArgs e)
    {
        cboFunctionLevel.Focus();
    }
    protected void cboFunctionLevel_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        txtGroupID.Focus();
    }
    protected void txtGroupID_TextChanged(object sender, EventArgs e)
    {
        txtOderal.Focus();
    }
    protected void txtOderal_TextChanged(object sender, EventArgs e)
    {
        txtWebScreen.Focus();
    }
    protected void txtWebScreen_TextChanged(object sender, EventArgs e)
    {
        radSysFunction.Focus();
    }
    protected void radSysFunction_CheckedChanged(object sender, EventArgs e)
    {
        radPublicFunction.Focus();
    }    
}